JavaScript Fetch Method Practice Exercise
This exercise helps you practise the basic fetch() workflow with a public test API.
The goal is to request posts from JSONPlaceholder, check the response, convert the response to JSON, and render the data on the page.
1. What you are practising
- selecting form and result elements
- listening for a submit event
- building query parameters with
URLSearchParams - sending a GET request with
fetch() - checking
response.ok - reading JSON with
response.json() - rendering API data into the DOM
- showing loading and error states
2. Fetch flow
Browser
-> fetch(url)
-> server receives request
-> server sends response
-> check response.ok
-> response.json()
-> render data
3. Basic pattern
fetch("https://jsonplaceholder.typicode.com/posts")
.then((response) => {
if (!response.ok) {
throw new Error(response.statusText);
}
return response.json();
})
.then((data) => {
console.log(data);
})
.catch((error) => {
console.error(error);
});
4. Add query parameters
JSONPlaceholder supports the _limit parameter. It controls how many posts come back.
const params = new URLSearchParams({
_limit: 5
});
const url = `https://jsonplaceholder.typicode.com/posts?${params}`;
5. Working practice version
Choose how many posts to load and click the button. Then read the script below the form and try rebuilding it from memory.
6. Practice steps
- Create variables for the form, status text, and list.
- Add a submit event listener to the form.
- Use
event.preventDefault()to stop the page reload. - Read
event.currentTarget.elements.limit.value. - Create a
URLSearchParamsobject with_limit. - Call
fetch()with the final URL. - Check
response.ok. - Return
response.json(). - Use
.then()to render the posts. - Use
.catch()to handle errors.
7. Important idea
fetch() does not give you the final data immediately. It gives you a Promise.
That means you work with the result inside .then(), or later with async and await.
const result = fetch(url);
console.log(result);
// Promise, not final posts data